package com.test.jwebsocket.websocket;

import org.apache.log4j.Logger;
import org.jwebsocket.api.WebSocketPacket;
import org.jwebsocket.kit.WebSocketServerEvent;
import org.jwebsocket.listener.WebSocketServerTokenEvent;
import org.jwebsocket.listener.WebSocketServerTokenListener;
import org.jwebsocket.logging.Logging;
import org.jwebsocket.token.Token;

public class JWebSocketTokenListenerSample implements
		WebSocketServerTokenListener {

	private static Logger log = Logging
			.getLogger(JWebSocketTokenListenerSample.class);

	public void processClosed(WebSocketServerEvent aEvent) {
		log.info("Client '" + aEvent.getSessionId() + "' disconnected.");

	}

	public void processOpened(WebSocketServerEvent aEvent) {
		log.info("Client '" + aEvent.getSessionId() + "' connected.");
	}

	public void processPacket(WebSocketServerEvent aEvent,
			WebSocketPacket aPacket) {
		// TODO Auto-generated method stub
	}

	public void processToken(WebSocketServerTokenEvent aEvent, Token aToken) {
		log.info("Client '" + aEvent.getSessionId() + "' sent Token: '"
				+ aToken.toString() + "'.");
		// here you can interpret the token type sent from the client according
		// to your needs.
		String lNS = aToken.getNS();
		String lType = aToken.getType();

		// check if token has a type and a matching namespace
		if (lType != null && "my.namespace".equals(lNS)) {
			// create a response token
			Token lResponse = aEvent.createResponse(aToken);
			if ("getInfo".equals(lType)) {
				// if type is "getInfo" return some server information
				lResponse.put("vendor", JWebSocketConstants.VENDOR);
				lResponse.put("version", JWebSocketConstants.VERSION_STR);
				lResponse.put("copyright", JWebSocketConstants.COPYRIGHT);
				lResponse.put("license", JWebSocketConstants.LICENSE);
			} else {
				// if unknown type in this namespace, return corresponding error
				// message
				lResponse.put("code", -1);
				lResponse.put("msg", "Token type '" + lType
						+ "' not supported in namespace '" + lNS + "'.");
			}
			aEvent.sendToken(lResponse);
		}
	}
}